/**
 * src/pages/guest/cart/index.tsx
 * ------------------------------------
 * 客人购物车页面
 * 1. 展示购物车中的菜品列表，支持修改数量与删除
 * 2. 实时计算总价，支持使用积分抵扣
 * 3. 提供下单功能，生成订单并跳转到订单确认页
 * 4. 底部导航切换至菜单/订单/个人中心
 * 仅客人角色可访问，依赖全局状态管理购物车数据
 * 创建日期：2025-08-06
 */
import { View, Text, Button, Input } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useState } from 'react'
import { useAppContext } from '../../../store'
import { formatPrice, generateId, calculateCartTotal } from '../../../utils'
import { OrderStatus } from '../../../types'
import './index.scss'

export default function GuestCart() {
  const { state, dispatch } = useAppContext()
  const { cart, currentUser } = state
  const [pointsToUse, setPointsToUse] = useState('0')

  const cartTotal = calculateCartTotal(cart)
  const maxPointsToUse = Math.min(currentUser?.points || 0, cartTotal)
  const pointsToUseNum = parseInt(pointsToUse) || 0
  const finalAmount = cartTotal - pointsToUseNum

  const handleUpdateQuantity = (dishId: string, quantity: number) => {
    if (quantity <= 0) {
      dispatch({ type: 'REMOVE_FROM_CART', payload: dishId })
    } else {
      dispatch({ type: 'UPDATE_CART_ITEM', payload: { dishId, quantity } })
    }
  }

  const handleRemoveItem = (dishId: string) => {
    dispatch({ type: 'REMOVE_FROM_CART', payload: dishId })
  }

  const handleCheckout = () => {
    if (cart.length === 0) {
      Taro.showToast({ title: '购物车为空', icon: 'error' })
      return
    }

    if (pointsToUseNum > maxPointsToUse) {
      Taro.showToast({ title: '积分使用超出限制', icon: 'error' })
      return
    }

    const order = {
      id: generateId(),
      userId: currentUser?.id || '',
      userName: currentUser?.name || '',
      items: cart.map(item => ({
        dishId: item.dishId,
        dishName: item.dishName,
        quantity: item.quantity,
        price: item.price,
        totalPrice: item.totalPrice
      })),
      totalAmount: cartTotal,
      pointsUsed: pointsToUseNum,
      finalAmount: finalAmount,
      status: 'pending' as OrderStatus,
      createdAt: new Date(),
      updatedAt: new Date()
    }

    dispatch({ type: 'ADD_ORDER', payload: order })
    dispatch({ type: 'CLEAR_CART' })
    
    // 更新用户积分
    if (currentUser) {
      const updatedUser = { ...currentUser, points: currentUser.points - pointsToUseNum }
      dispatch({ type: 'SET_USER', payload: updatedUser })
    }

    Taro.showToast({ title: '下单成功', icon: 'success' })
    Taro.navigateTo({ url: '/pages/guest/orders/index' })
  }

  const handleViewMenu = () => {
    Taro.navigateTo({ url: '/pages/guest/menu/index' })
  }

  const handleViewOrders = () => {
    Taro.navigateTo({ url: '/pages/guest/orders/index' })
  }

  const handleViewProfile = () => {
    Taro.navigateTo({ url: '/pages/guest/profile/index' })
  }

  return (
    <View className='guest-cart'>
      <View className='header'>
        <View className='header-left'>
          <Text className='title'>购物车</Text>
        </View>
      </View>

      {cart.length === 0 ? (
        <View className='empty-cart'>
          <Text className='empty-icon'>🛒</Text>
          <Text className='empty-text'>购物车是空的</Text>
          <Text className='empty-desc'>快去选择一些美味的菜品吧！</Text>
          <Button className='go-menu-btn' onClick={handleViewMenu}>
            去点餐
          </Button>
        </View>
      ) : (
        <>
          <View className='cart-items'>
            {cart.map(item => (
              <View key={item.dishId} className='cart-item'>
                <View className='item-info'>
                  <Text className='item-name'>{item.dishName}</Text>
                  <Text className='item-price'>{formatPrice(item.price)}</Text>
                </View>
                
                <View className='item-actions'>
                  <View className='quantity-controls'>
                    <Button 
                      className='quantity-btn'
                      onClick={() => handleUpdateQuantity(item.dishId, item.quantity - 1)}
                    >
                      -
                    </Button>
                    <Text className='quantity'>{item.quantity}</Text>
                    <Button 
                      className='quantity-btn'
                      onClick={() => handleUpdateQuantity(item.dishId, item.quantity + 1)}
                    >
                      +
                    </Button>
                  </View>
                  
                  <Button 
                    className='remove-btn'
                    onClick={() => handleRemoveItem(item.dishId)}
                  >
                    删除
                  </Button>
                </View>
              </View>
            ))}
          </View>

          <View className='checkout-section'>
            <View className='points-section'>
              <Text className='points-label'>使用积分抵扣</Text>
              <Input
                className='points-input'
                type='number'
                placeholder={`最多可使用 ${maxPointsToUse} 积分`}
                value={pointsToUse}
                onInput={(e) => setPointsToUse(e.detail.value)}
              />
            </View>
            
            <View className='total-section'>
              <View className='total-row'>
                <Text className='total-label'>商品总额</Text>
                <Text className='total-amount'>{formatPrice(cartTotal)}</Text>
              </View>
              {pointsToUseNum > 0 && (
                <View className='total-row'>
                  <Text className='total-label'>积分抵扣</Text>
                  <Text className='total-amount'>-{formatPrice(pointsToUseNum)}</Text>
                </View>
              )}
              <View className='total-row'>
                <Text className='total-label'>实付金额</Text>
                <Text className='total-amount final'>{formatPrice(finalAmount)}</Text>
              </View>
            </View>
            
            <Button 
              className='checkout-btn'
              onClick={handleCheckout}
              disabled={cart.length === 0}
            >
              立即下单
            </Button>
          </View>
        </>
      )}

      {/* 底部导航栏 */}
      <View className='bottom-nav'>
        <View className='nav-item' onClick={handleViewMenu}>
          <Text className='nav-icon'>🍽️</Text>
          <Text className='nav-text'>菜单</Text>
        </View>
        <View className='nav-item active' onClick={() => {}}>
          <Text className='nav-icon'>🛒</Text>
          <Text className='nav-text'>购物车</Text>
          {cart.length > 0 && (
            <View className='nav-badge'>{cart.length}</View>
          )}
        </View>
        <View className='nav-item' onClick={handleViewOrders}>
          <Text className='nav-icon'>📋</Text>
          <Text className='nav-text'>订单</Text>
        </View>
        <View className='nav-item' onClick={handleViewProfile}>
          <Text className='nav-icon'>👤</Text>
          <Text className='nav-text'>我的</Text>
        </View>
      </View>
    </View>
  )
} 